package cyz.text.textactivity.core.handler;

import androidx.annotation.NonNull;

public class CyzHandler {

    private CyzLooper cyzLooper;
    private CyzMessageQueue cyzMessageQueue;

    public CyzHandler() {
        cyzLooper = CyzLooper.myLooper();
        if (cyzLooper == null) {
            throw new RuntimeException(
                    "Can't create handler inside thread " + Thread.currentThread()
                            + " that has not called Looper.prepare()");
        }
        cyzMessageQueue  = cyzLooper.mQueue;
    }

    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(@NonNull CyzMessage msg) {
    }

    public void sendMessage(CyzMessage message) {
        //将消息放入消息队列中
        enqueueMessage(message);
    }

    private void enqueueMessage(CyzMessage message) {
        //赋值当前消息
        message.target = this;
        //将cyzMessageQueue,将消息传入
        cyzMessageQueue.enqueueMessage(message);
    }


    public void dispatchMessage(CyzMessage cyzMessage) {
        handleMessage(cyzMessage);
    }
}
